package com.shinji.tratu;

import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

public class RecentFragment extends Fragment implements LookupAction,
		DatasetChanged {
	private MainActivity mainActivity;
	private ListView mListView;
	private ArrayList<Word> listWords;
	private ArrayList<Word> drawingWords = new ArrayList<Word>();
	private static final String TAG = "RecentFragment";
	private DicRecentWordsAdapter adapter;
	private AdView mAdView;
	private static RecentFragment instance;
	private WordComparator comparator;
	SharedPreferences mPref;
	Editor editor;
	boolean disableAd = false; // co vo hieu hoa quang cao khong
	public static RecentFragment getInstance() {
		return instance;
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mainActivity = (MainActivity) activity;
		Tracker t = ((AnalyticsSampleApp) mainActivity.getApplication())
				.getTracker(AnalyticsSampleApp.TrackerName.APP_TRACKER);
		t.setScreenName(TAG);
		t.send(new HitBuilders.AppViewBuilder().build());
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		comparator = new WordComparator();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View layoutView = inflater.inflate(R.layout.dic_recent_fragment,
				container, false);
		mListView = (ListView) layoutView.findViewById(R.id.recent_listView);
		instance = this;
		mAdView = (AdView) layoutView.findViewById(R.id.adView);
		if (disableAd) {
			mAdView.setVisibility(View.GONE);
			Log.i(TAG, "disable ad");
		} else {
			mAdView.setAdListener(new ToastAdListener(mainActivity));
			mAdView.loadAd(new AdRequest.Builder().build());
		}
		return layoutView;
	}

	@Override
	public void onPause() {
		super.onPause();
		if (!disableAd)
			mAdView.pause();
	}

	// @Override
	// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
	// // TODO Auto-generated method stub
	// // inflater.inflate(R.menu.menu_recent, menu);
	//
	// super.onCreateOptionsMenu(menu, inflater);
	// }

	// @Override
	// public void onPrepareOptionsMenu(Menu menu) {
	// // TODO Auto-generated method stub
	// super.onPrepareOptionsMenu(menu);
	// }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		return super.onOptionsItemSelected(item);

	}

	@Override
	public void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
		disableAd = ToastAdListener.isAdDisable(mainActivity);
		if (disableAd) {
			mAdView.setVisibility(View.GONE);
			Log.i(TAG, "disable ad");
		} else {
			mAdView.setVisibility(View.VISIBLE);
			mAdView.resume();
		}
		listWords = mainActivity.getListWords();
		// mainActivity.setLookupAction(this);
		drawingWords = listWords;
		adapter = new DicRecentWordsAdapter(mainActivity, drawingWords);
		mListView.setAdapter(adapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Log.i(TAG, "click " + position);
				Intent intent = new Intent(mainActivity,
						WordDetailActivity.class);
				intent.putExtra("wordId", (int) listWords.get(position).getId());
				startActivity(intent);
			}
		});
		mListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				showDeleteDialog(listWords.get(arg2));
				return false;
			}
		});
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (!disableAd)
			mAdView.destroy();
	}

	@Override
	public void wantToLookup(String word) {
		drawingWords = Util.searchInListWordsByKey(listWords, word);
		Collections.sort(drawingWords, comparator);
		adapter.setListWords(drawingWords);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onQueryTextChange(String newText) {
		drawingWords = Util.searchInListWordsByKey(listWords, newText);
		Collections.sort(drawingWords, comparator);
		adapter.setListWords(drawingWords);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void notifyDatasetChanged() {
		adapter.notifyDataSetChanged();
	}

	private void showDeleteDialog(final Word word) {
		LayoutInflater inflater = (LayoutInflater) mainActivity
				.getBaseContext().getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.delete_dialog, null);
		final AlertDialog alertDialog = new AlertDialog.Builder(mainActivity)
				.setView(layout).create();
		alertDialog.show();
		Button okButton = (Button) layout.findViewById(R.id.delete_ok);
		okButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				listWords.remove(word);
				mainActivity.getWordDatabase().deleteAWord(word.getId());
				adapter.setListWords(listWords);
				adapter.notifyDataSetChanged();
				alertDialog.dismiss();
			}
		});
		Button cancelButton = (Button) layout.findViewById(R.id.delete_cancel);
		cancelButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
			}
		});
		Button deleteAllButton = (Button) layout.findViewById(R.id.delete_all);
		deleteAllButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				listWords.clear();
				mainActivity.getWordDatabase().deleteAll();
				adapter.setListWords(listWords);
				adapter.notifyDataSetChanged();
				alertDialog.dismiss();
			}
		});
	}

	/**
	 * trong truong hop xoa tat ca
	 */
	public void onDeleteAll() {
		listWords.clear();
		adapter.setListWords(listWords);
		adapter.notifyDataSetChanged();
	}

}
